﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Common;
using Taobao.Top.Api;
using Taobao.Top.Api.Request;
using Taobao.Top.Api.Domain;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Xml;
using System.Web.Security;

public partial class top_crm_missionadd : System.Web.UI.Page
{
    public string session = string.Empty;
    public string nick = string.Empty;
    public string id = string.Empty;
    public string now = string.Empty;
    public string totalcustomer = string.Empty;

    public string count2 = string.Empty;
    public string count3 = string.Empty;
    public string count4 = string.Empty;
    public string count5 = string.Empty;
    public string count6 = string.Empty;
    public string count7 = string.Empty;
    public string count8 = string.Empty;
    public string count9 = string.Empty;
    public string groupstr = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        string id = utils.NewRequest("id", utils.RequestType.QueryString);
        Common.Cookie cookie = new Common.Cookie();
        string taobaoNick = cookie.getCookie("nick");
        session = cookie.getCookie("top_sessiongroupbuy");
        string iscrm = cookie.getCookie("iscrm");
        Rijndael_ encode = new Rijndael_("tetesoft");
        nick = encode.Decrypt(taobaoNick);


        //过期判断
        if (string.IsNullOrEmpty(taobaoNick))
        {
            string msg = "尊敬的淘宝卖家，非常抱歉的告诉您，您还没有购买此服务或者登录信息已失效，如需继续使用请<a href='http://fuwu.taobao.com/serv/detail.htm?service_id=4545' target='_blank'>进入该服务</a>，谢谢！";
            Response.Redirect("buy.aspx?msg=" + HttpUtility.UrlEncode(msg));
            Response.End();
            return;
        }


        //过期判断
        if (!IsBuy(nick))
        {

            string msg = "尊敬的" + nick + "，非常抱歉的告诉您，只有VIP版本才能使用【客户关系营销】功能，如需继续使用请<a href='http://fuwu.taobao.com/ser/detail.htm?service_code=service-0-22904&frm=haoping' target='_blank'>购买高级会员服务</a>，谢谢！";
            Response.Redirect("buy.aspx?msg=" + HttpUtility.UrlEncode(msg));
            Response.End();
            return;
        }

        if (!IsPostBack)
        {
            now = DateTime.Now.AddHours(1).ToString();

            string sql = string.Empty;
            sql = "SELECT * FROM TCS_Group WHERE nick = '" + nick + "' AND isdel = 0";
            DataTable dt = utils.ExecuteDataTable(sql);

            string appkey = "12159997";
            string secret = "614e40bfdb96e9063031d1a9e56fbed5";

            IDictionary<string, string> param = new Dictionary<string, string>();
            param.Add("page_size", "100");
            param.Add("current_page", "1");

            string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.groups.get", session, param);
            Regex reg = new Regex(@"<group>([\s\S]*?)</group>", RegexOptions.IgnoreCase);
            MatchCollection match = reg.Matches(result);

            for (int i = 0; i < match.Count; i++)
            {
                string str = match[i].Groups[0].ToString();
                string groupid = GetValueByProperty(str, "group_id");
                string groupName = GetValueByProperty(str, "group_name");
                string groupCount = GetValueByProperty(str, "member_count");

                //如果数据库内有记录则显示
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    if (groupid == dt.Rows[j]["taobaoid"].ToString())
                    {
                        //row["price"] = dt.Rows[j]["price"];
                        //row["priceend"] = dt.Rows[j]["priceend"];
                        //row["arealist"] = InitAreaStr(dt.Rows[j]["arealist"].ToString());
                        //row["actdate"] = dt.Rows[j]["actdate"];
                        //row["actdateend"] = dt.Rows[j]["actdateend"];
                        groupstr += "<option value='" + groupid + "' title='" + groupCount + "'>" + groupName + "</option>";
                    }
                }
            }
        }
    }

    public static string GetValueByProperty(string str, string prop)
    {
        Regex reg = new Regex(@"<" + prop + @">([^<]*)</" + prop + @">", RegexOptions.IgnoreCase);
        if (reg.IsMatch(str))
        {
            return reg.Match(str).Groups[1].ToString();
        }
        else
        {
            return "";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string guid = Guid.NewGuid().ToString();
        string sql = string.Empty;
        string typ = utils.NewRequest("typ", utils.RequestType.Form);
        string group = utils.NewRequest("group", utils.RequestType.Form);
        string groupguid = utils.NewRequest("groupguid", utils.RequestType.Form);
        string cuicontent = utils.NewRequest("cuicontent", utils.RequestType.Form);
        string cuidate = utils.NewRequest("cuidate", utils.RequestType.Form);
        string birthdaycontent = utils.NewRequest("birthdaycontent", utils.RequestType.Form);
        string backdate = utils.NewRequest("backdate", utils.RequestType.Form);
        string backcontent = utils.NewRequest("backcontent", utils.RequestType.Form);
        string actdate = utils.NewRequest("actdate", utils.RequestType.Form);
        string actcontent = utils.NewRequest("actcontent", utils.RequestType.Form);
        string isstop = utils.NewRequest("isstop", utils.RequestType.Form);
        string sendnow = utils.NewRequest("sendnow", utils.RequestType.Form);

        //新增催单短信判定
        string startsend = utils.NewRequest("startsend", utils.RequestType.Form);
        string endsend = utils.NewRequest("endsend", utils.RequestType.Form);
        string price = utils.NewRequest("price", utils.RequestType.Form);
        string ispayone = utils.NewRequest("ispayone", utils.RequestType.Form);
        string isclose = utils.NewRequest("isclose", utils.RequestType.Form);

        //新增指定商品发送判定
        string productid = utils.NewRequest("productid", utils.RequestType.Form);
        string orderstatus = utils.NewRequest("orderstatus", utils.RequestType.Form);


        //判断是否有同类型活动
        sql = "SELECT COUNT(*) FROM TCS_Mission WHERE nick = '" + nick + "' AND typ = '" + typ + "' AND grade = '" + (groupguid == "" ? "0" : groupguid) + "' AND isdel = 0";
        string count = utils.ExecuteString(sql);
        if (count != "0")
        {
            Response.Write("<script>alert('已经有同类型的服务在执行中了！');history.go(-1);</script>");
            Response.End();
            return;
        }

        string black = string.Empty;
        //判断是否为黑词
        if (CheckIsBlack(cuicontent, ref black) || CheckIsBlack(birthdaycontent, ref black) || CheckIsBlack(backcontent, ref black) || CheckIsBlack(actcontent, ref black))
        {
            Response.Write("<script>alert('短信内容包含黑词“" + black + "”！');history.go(-1);</script>");
            Response.End();
            return;
        }

        switch (typ)
        {
            case "unpay":
                if (cuicontent.Length == 0)
                {
                    Response.Write("<script>alert('请填写内容！');history.go(-1);</script>");
                    Response.End();
                    return;
                }

                sql = "INSERT INTO TCS_Mission (guid, nick, typ, content, grade, timecount,isstop,startsend,endsend,price,ispayone,isclose) VALUES ('" + guid + "','" + nick + "','" + typ + "','" + cuicontent + "','" + group + "','" + cuidate + "','" + isstop + "','" + startsend + "','" + endsend + "','" + price + "','" + ispayone + "','" + isclose + "')";
                break;
            case "birthday":
                if (birthdaycontent.Length == 0)
                {
                    Response.Write("<script>alert('请填写内容！');history.go(-1);</script>");
                    Response.End();
                    return;
                }
                sql = "INSERT INTO TCS_Mission (guid, nick, typ, content, grade,isstop) VALUES ('" + guid + "','" + nick + "','" + typ + "','" + birthdaycontent + "','" + group + "','" + isstop + "')";
                break;
            case "back":
                if (backcontent.Length == 0)
                {
                    Response.Write("<script>alert('请填写内容！');history.go(-1);</script>");
                    Response.End();
                    return;
                }
                sql = "INSERT INTO TCS_Mission (guid, nick, typ, content, grade, timecount,isstop) VALUES ('" + guid + "','" + nick + "','" + typ + "','" + backcontent + "','" + group + "','" + backdate + "','" + isstop + "')";
                break;
            case "act":
                if (actcontent.Length == 0)
                {
                    Response.Write("<script>alert('请填写内容！');history.go(-1);</script>");
                    Response.End();
                    return;
                }

                //如果是立即发送
                if (sendnow == "1")
                {
                    actdate = DateTime.Now.ToString();
                }

                //清理并加入临时数据处理
                InitNewCustomerAct(typ, guid, actcontent, groupguid, actdate, isstop);

                //SendMutiMsg(actcontent, groupguid);

                break;
            case "item":
                if (actcontent.Length == 0)
                {
                    Response.Write("<script>alert('请填写内容！');history.go(-1);</script>");
                    Response.End();
                    return;
                }

                //如果是立即发送
                if (sendnow == "1")
                {
                    actdate = DateTime.Now.ToString();
                }

                //清理并加入临时数据处理
                InitNewCustomerActItem(typ, guid, actcontent, productid, orderstatus, actdate, isstop);

                //SendMutiMsg(actcontent, groupguid);

                break;
        }

        utils.ExecuteNonQuery(sql);

        sql = "SELECT COUNT(*) FROM TCS_Mission WHERE nick = '" + nick + "' AND typ = '" + typ + "' AND grade = '" + (groupguid == "" ? "0" : groupguid) + "' AND isdel = 0";
        count = utils.ExecuteString(sql);
        if (count != "0")
        {
            Response.Write("<script>alert('已经有同类型的服务在执行中了！');history.go(-1);</script>");
            Response.End();
            return;
        }

        //Response.Write(sql);
        //Response.Redirect("missionlist.aspx");
        Response.Write("<script>alert('创建成功！');window.location.href='missionlist.aspx';</script>");
        Response.End();
    }


    private void InitNewCustomerActItem(string typ, string guid, string actcontent, string productid, string orderstatus, string actdate, string isstop)
    {
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string sql = string.Empty;
        string result = string.Empty;
        int total = 0;
        IDictionary<string, string> param = new Dictionary<string, string>();

        param.Add("fields", "receiver_mobile, orders.num_iid, created, consign_time, total_fee, payment, promotion_details, type, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, status, buyer_area, orders.oid, orders.refund_id, payment, buyer_rate");
        param.Add("tid", "212281132117937");
    }


    private void InitNewCustomerAct(string typ, string guid, string actcontent, string groupguid, string actdate, string isstop)
    {
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        string sql = string.Empty;
        string result = string.Empty;
        int total = 0;
        IDictionary<string, string> param = new Dictionary<string, string>();
        //加入当前选择会员到临时会员组

        for (int i = 1; i < 9999; i++)
        {
            //获取买家分组信息
            param = new Dictionary<string, string>();
            param.Add("page_size", "100");
            param.Add("current_page", i.ToString());
            param.Add("relation_source", "1");
            param.Add("order", "lastest_time");
            param.Add("sort", "desc");
            if (groupguid == "1" || groupguid == "2" || groupguid == "3" || groupguid == "4")
            {
                param.Add("grade", groupguid);
            }
            else if (groupguid == "")
            {
                //所有会员
            }
            else
            {
                param.Add("group_id", groupguid);
            }

            result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.members.search", session, param);
            Regex reg = new Regex(@"<crm_member>([\s\S]*?)</crm_member>", RegexOptions.IgnoreCase);
            MatchCollection match = reg.Matches(result);
            //如果没有了则退出
            if (match.Count == 0)
            {
                break;
            }
            //新版会员信息获取
            WebClient c = new WebClient();
            c.Encoding = Encoding.UTF8;
            string resultApi = string.Empty;
            string buynickList = string.Empty;

            for (int j = 0; j < match.Count; j++)
            {
                string strCus = match[j].Groups[0].ToString();
                string buynick = GetValueByProperty(strCus, "buyer_nick");
                if (j == 0)
                {
                    buynickList = buynick;
                }
                else
                {
                    buynickList += "|" + buynick;
                }
            }

             //通过内部地址查询
            string url = "http://cusapi.7fshop.com/cusapi.aspx?act=select&buynick=" + HttpUtility.UrlEncode(buynickList);
            try
            {
                resultApi = c.DownloadString(url);
            }
            catch 
            {
                for (i = 0; i < 100;i++ )
                {
                    resultApi += "nodata,";
                }
            }
            string[] cusAry = resultApi.Split(',');

            //Response.Write(url + "\r\n\r\n");
            //Response.Write(resultApi + "\r\n\r\n" + "\r\n\r\n");

            

            //循环更新
            for (int j = 0; j < match.Count; j++)
            {
                string strCus = match[j].Groups[0].ToString();
                string buynick = GetValueByProperty(strCus, "buyer_nick");
                string lastTrade = GetValueByProperty(strCus, "last_trade_time");
                string phone = string.Empty;
                string truename = string.Empty;

                try
                {
                    if (cusAry[j] != "nodata")
                    {
                        string[] ary = cusAry[j].Split('|');
                        if (ary.Length > 1)
                        {
                            phone = ary[0];
                            truename = ary[1];
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else
                    {
                        //如果上次交易时间超过3个月则直接跳过无需调用此接口
                        if (DateTime.Parse(lastTrade).AddMonths(3) < DateTime.Now)
                        {
                            Response.Write(buynick + "<br>");
                            continue;
                        }

                        //再获取买家手机号，如果没有跳过继续
                        param = new Dictionary<string, string>();
                        param.Add("fields", "receiver_mobile,receiver_name");
                        param.Add("nick", nick);
                        param.Add("buyer_nick", buynick);
                        param.Add("page_size", "1");
                        string traderesult = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.trades.sold.get", session, param);
                        //Response.Write(traderesult + "\r\n\r\n");
                        phone = GetValueByProperty(traderesult, "receiver_mobile");
                        truename = GetValueByProperty(traderesult, "receiver_name");
                        if (phone == "")
                        {
                            continue;
                        }
                    }

                    //加入临时会员
                    sql = "INSERT INTO TCS_MsgSendTmp (nick, buynick, mobile, truename, missionid) VALUES ('" + nick + "','" + buynick + "','" + phone + "','" + truename + "','" + guid + "')";
                    utils.ExecuteNonQuery(sql);
                    total++;
                }
                catch
                {
                    //Response.Write(j.ToString() + "<br>");
                }
            }
        }

        sql = "INSERT INTO TCS_Mission (guid, nick, typ, content, grade, senddate,isstop,totalcount) VALUES ('" + guid + "','" + nick + "','" + typ + "','" + actcontent + "','" + groupguid + "','" + actdate + "','" + isstop + "','" + total.ToString() + "')";
        ////更新任务会员总数
        //sql = "UPDATE TCS_Mission SET totalcount = '" + total.ToString() + "' WHERE guid = '" + guid + "'";
        utils.ExecuteNonQuery(sql);

        Response.Write("<script>alert('营销任务创建成功！');window.location.href='missionlist.aspx';</script>");
    }

    private bool CheckIsBlack(string p, ref string black)
    {
        string sql = "SELECT * FROM TCS_BlackWord";
        DataTable dt = utils.ExecuteDataTable(sql);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (p.IndexOf(dt.Rows[i]["word"].ToString()) != -1)
            {
                black = dt.Rows[i]["word"].ToString();
                return true;
            }
        }

        return false;
    }

    /// <summary>
    /// 短信群发
    /// </summary>
    /// <param name="actcontent"></param>
    private void SendMutiMsg(string actcontent, string groupguid)
    {
        string sql = string.Empty;
        if (groupguid == "0")
        {
            sql = "SELECT * FROM TCS_Customer WHERE nick = '" + nick + "' AND LEN(mobile) > 0";
        }
        else
        {
            sql = "SELECT * FROM TCS_Customer WHERE nick = '" + nick + "' AND LEN(mobile) > 0 AND groupguid = '" + groupguid + "'";
        }
        DataTable dt = utils.ExecuteDataTable(sql);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            //判断是否还有短信可发
            sql = "SELECT total FROM TCS_ShopConfig WITH (NOLOCK) WHERE nick = '" + nick + "'";
            string total = utils.ExecuteString(sql);

            if (int.Parse(total) > 0)
            {
                string buynick = dt.Rows[i]["buynick"].ToString();
                string mobile = dt.Rows[i]["mobile"].ToString();

                sql = "SELECT COUNT(*) FROM TCS_MsgSend WHERE buynick = '" + buynick + "' AND nick = '" + nick + "' AND typ = 'act' AND DATEDIFF(d, adddate, GETDATE()) = 0";
                string count = utils.ExecuteString(sql);
                if (count == "0")
                {
                    //强行截取
                    if (actcontent.Length > 66)
                    {
                        actcontent = actcontent.Substring(0, 66);
                    }

                    string result = SendMessage(mobile, actcontent);
                    if (result != "0")
                    {
                        string number = "1";

                        //记录短信发送记录
                        sql = "INSERT INTO TCS_MsgSend (" +
                                            "nick, " +
                                            "buynick, " +
                                            "mobile, " +
                                            "[content], " +
                                            "yiweiid, " +
                                            "num, " +
                                            "typ " +
                                        " ) VALUES ( " +
                                            " '" + nick + "', " +
                                            " '" + buynick + "', " +
                                            " '" + mobile + "', " +
                                            " '" + actcontent.Replace("'", "''") + "', " +
                                            " '" + result + "', " +
                                            " '" + number + "', " +
                                            " 'act' " +
                                        ") ";
                        if (mobile.Length != 0)
                        {
                            utils.ExecuteNonQuery(sql);
                        }

                        //更新短信数量
                        sql = "UPDATE TCS_ShopConfig SET used = used + " + number + ",total = total-" + number + " WHERE nick = '" + nick + "'";
                        utils.ExecuteNonQuery(sql);
                    }
                }
            }
        }
    }

    public static string UrlEncode(string str)
    {
        StringBuilder sb = new StringBuilder();
        byte[] byStr = System.Text.Encoding.Default.GetBytes(str);
        for (int i = 0; i < byStr.Length; i++)
        {
            sb.Append(@"%" + Convert.ToString(byStr[i], 16));
        }

        return (sb.ToString());
    }

    public static string MD5AAA(string str)
    {
        return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
    }

    public string SendMessage(string phone, string msg)
    {
        //有客户没有手机号也发送短信
        if (phone.Length == 0)
        {
            return "0";
        }

        string uid = "ZXHD-SDK-0107-XNYFLX";
        string pass = MD5AAA("WEGXBEPY").ToLower();

        msg = UrlEncode(msg);

        string param = "regcode=" + uid + "&pwd=" + pass + "&phone=" + phone + "&CONTENT=" + msg + "&extnum=11&level=1&schtime=null&reportflag=1&url=&smstype=0&key=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] bs = Encoding.ASCII.GetBytes(param);

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://sms.pica.com:8082/zqhdServer/sendSMS.jsp" + "?" + param);

        req.Method = "GET";

        using (HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse())
        {
            using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("GB2312")))
            {
                string content = reader.ReadToEnd();

                if (content.IndexOf("<result>0</result>") == -1)
                {
                    //发送失败
                    return content;
                }
                else
                {
                    //发送成功
                    Regex reg = new Regex(@"<sid>([^<]*)</sid>", RegexOptions.IgnoreCase);
                    MatchCollection match = reg.Matches(content);
                    string number = "888888";// match[0].Groups[1].ToString();
                    return number;
                }
            }
        }
    }


    /// <summary>
    /// 判断该用户是否订购了该服务
    /// </summary>
    /// <param name="nick"></param>
    /// <returns></returns>
    private bool IsBuy(string nick)
    {
        string sql = "SELECT plus FROM TCS_ShopSession WHERE nick = '" + nick + "'";
        DataTable dt = utils.ExecuteDataTable(sql);
        if (dt.Rows.Count != 0)
        {
            string plus = dt.Rows[0][0].ToString();
            if (plus.IndexOf("crm") != -1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }


    #region TOP API
    /// <summary> 
    /// 给TOP请求签名 API v2.0 
    /// </summary> 
    /// <param name="parameters">所有字符型的TOP请求参数</param> 
    /// <param name="secret">签名密钥</param> 
    /// <returns>签名</returns> 
    protected static string CreateSign(IDictionary<string, string> parameters, string secret)
    {
        parameters.Remove("sign");
        IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
        IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
        StringBuilder query = new StringBuilder(secret);
        while (dem.MoveNext())
        {
            string key = dem.Current.Key;
            string value = dem.Current.Value;
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
            {
                query.Append(key).Append(value);
            }
        }
        query.Append(secret);
        MD5 md5 = MD5.Create();
        byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            string hex = bytes[i].ToString("X");
            if (hex.Length == 1)
            {
                result.Append("0");
            }
            result.Append(hex);
        }
        return result.ToString();
    }
    /// <summary> 
    /// 组装普通文本请求参数。 
    /// </summary> 
    /// <param name="parameters">Key-Value形式请求参数字典</param> 
    /// <returns>URL编码后的请求数据</returns> 
    protected static string PostData(IDictionary<string, string> parameters)
    {
        StringBuilder postData = new StringBuilder();
        bool hasParam = false;
        IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
        while (dem.MoveNext())
        {
            string name = dem.Current.Key;
            string value = dem.Current.Value;
            // 忽略参数名或参数值为空的参数 
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
            {
                if (hasParam)
                {
                    postData.Append("&");
                }
                postData.Append(name);
                postData.Append("=");
                postData.Append(Uri.EscapeDataString(value));
                hasParam = true;
            }
        }
        return postData.ToString();
    }
    /// <summary> 
    /// TOP API POST 请求 
    /// </summary> 
    /// <param name="url">请求容器URL</param> 
    /// <param name="appkey">AppKey</param> 
    /// <param name="appSecret">AppSecret</param> 
    /// <param name="method">API接口方法名</param> 
    /// <param name="session">调用私有的sessionkey</param> 
    /// <param name="param">请求参数</param> 
    /// <returns>返回字符串</returns> 
    public static string Post(string url, string appkey, string appSecret, string method, string session,
    IDictionary<string, string> param)
    {
        #region -----API系统参数----
        param.Add("app_key", appkey);
        param.Add("method", method);
        param.Add("session", session);
        param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        param.Add("format", "xml");
        param.Add("v", "2.0");
        param.Add("sign_method", "md5");
        param.Add("sign", CreateSign(param, appSecret));
        #endregion
        string result = string.Empty;
        #region ---- 完成 HTTP POST 请求----
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.KeepAlive = true;
        req.Timeout = 300000;
        req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
        byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(postData, 0, postData.Length);
        reqStream.Close();
        HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
        Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
        Stream stream = null;
        StreamReader reader = null;
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        result = reader.ReadToEnd();
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
        #endregion
        return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");
    }
    #endregion
}